package com.cqut.util;

import java.io.*;
import java.nio.charset.Charset;
import java.util.*;

import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 *	Author:TracyQiu
 *		
 * 	上传文件
 **/
public class FileUploadServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {

		response.setContentType("text/html; charset=utf-8");
		response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();

		try {
			final long MAX_SIZE = 10 * 1024 * 1024;// 设置上传文件最大为 10M
			final String[] allowtype = new String[] { "xls", "xlsx", "zip" };  //设置上传的文件的扩展名

			// 实例化一个硬盘文件工厂,用来配置上传组件ServletFileUpload
			DiskFileItemFactory dfif = new DiskFileItemFactory();
			ServletFileUpload fu = new ServletFileUpload(dfif);
			fu.setHeaderEncoding("utf-8");
			dfif.setSizeThreshold(4096000);// 设置上传文件时用于临时存放文件的内存大小,这里是4K.多于的部分将临时存在硬盘

//			String uptemp = Config.getContextRealPath() + "Upload" + "/";
			String webRoot = this.getServletContext().getRealPath("/");
			//获得上传文件目的地的路径
			String uptemp = webRoot + "Uploads/";  

			dfif.setRepository(new File(uptemp));// 设置存放临时文件的目录,web根目录下的uploadtemp目录
			fu.setSizeMax(MAX_SIZE);
			List fileItems = null;
			try {
				fileItems = fu.parseRequest(request); // 得到所有的文件：
			} catch (FileUploadException e) // 处理文件尺寸过大异常
			{
				if (e instanceof SizeLimitExceededException) {
					out.println("<script>alert('文件尺寸超过规定大小');</script>");
					return;
				}
				e.printStackTrace();
			}

			if (fileItems == null || fileItems.size() == 0) // 没有文件上传
			{
				out.println("<script>alert('请选择上传文件');</script>");
				return;
			}

			Iterator i = fileItems.iterator();
			// 依次处理每一个文件：
			while (i.hasNext()) {
				long size = 0;

				FileItem fi = (FileItem) i.next();

				if (fi == null)
					continue;
				// 忽略简单form字段而不是上传域的文件域(<input type="text" />等)
				if (fi.isFormField()) {

					String name = fi.getFieldName();
					if (name != null) {
						name = new String(name.getBytes(Charset
								.defaultCharset().displayName()), "utf-8");
					}
					String value = fi.getString();
					continue;
				}

				// 获得文件名，这个文件名包括路径：
				String path = fi.getName();
				size = fi.getSize();
				if ("".equals(path) || size == 0) {
					out.println("<script>alert('请选择上传文件');</script>");
					return;
				}
				// 得到去除路径的文件名
				String t_name = path.substring(path.lastIndexOf("\\") + 1);
				// 得到文件的扩展名(无扩展名时将得到全名)
				String t_ext = t_name.substring(t_name.lastIndexOf(".") + 1);

				// 拒绝接受规定文件格式之外的文件类型
				int allowFlag = 0;
				int allowedExtCount = allowtype.length;
				for (allowFlag = 0; allowFlag < allowedExtCount; allowFlag++) {
					if (allowtype[allowFlag].equals(t_ext))
						break;
				}

				if (allowFlag == allowedExtCount) {
					String message = "";
					for (allowFlag = 0; allowFlag < allowedExtCount; allowFlag++) {
						message += "*." + allowtype[allowFlag] + " ";
					}
					return;
				}

				// 保存的最终文件完整路径,保存在web根目录下的upload目录下
				String u_name = webRoot + "Upload/"
						+ t_name;
				// 原来的文件名

				path = webRoot + "Upload/" + path;
				try {
					// 保存文件
					fi.write(new File(u_name));
					out.println("<script>alert('操作成功');</script>");
					out.println("{message:\"文件上传成功. 已保存为: " + t_name
							+ " 文件大小: " + size + "字节\"} <br>");
				} catch (Exception e) {
					out.println("<script>alert('操作失败');</script>");
					e.printStackTrace();
				}

			}
			// 跳转到上传成功提示页面
		} catch (Exception e) {
			// 可以跳转出错页面
		}
	}
}